/**
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package com.tasktodorid;

import java.util.List;
import java.util.Map;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.tasktodorid.util.ConstUtil;
import com.tasktodorid.util.TodoUtil;

/**
 * Todorid的主启动程序
 *
 * @author qu sheng
 *
 */
public class TaskTodo extends ListActivity {

    /**
     * 显示Debug用的TAG
     */
    private static String TAG = TaskTodo.class.getName();

    /**
     * 显示所有目录的ListView
     */
    ListView listCatalog;

    /**
     * 显示全部信息的ListView
     */
    ListView listMain;

    /**
     * 全部信息上的TextView
     */
    TextView txtAllTitle;

    /**
     * 目录信息上的TextView
     */
    TextView txtAllCatalog;

    private static final int DIALOG_ADD_CATALOG = 0;

    /**
     * Activity的OnCreate Event
     *
     * @param Bundle
     *            句柄
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.todomain);

        // 数据库Standby
        standby();

        // 初始化画面控件
        initCtrl();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int iSelectItemId = item.getItemId();
        switch (iSelectItemId) {
        case R.id.menuNewCatalog:
            showDialog(DIALOG_ADD_CATALOG);
            break;
        case R.id.menuAbout:
            break;
        case R.id.menuExit:
            this.finish();
            break;
        }

        return true;
    }

    @Override
    public void onListItemClick(ListView listView, View view, int position, long id) {
        SimpleAdapter adapter = (SimpleAdapter)listView.getAdapter();
        Map data = (Map) adapter.getItem(position);
        Intent it = new Intent(TaskTodo.this, TasksList.class);
        Bundle bundle = new Bundle();
        bundle.putInt(ConstUtil.TASKS_MODE_LIST_KEY, TasksList.MODE_CATALOGS);
        bundle.putString("cid", (String)data.get("cid"));
        it.putExtras(bundle);
        startActivity(it);
    }


    @Override
    protected Dialog onCreateDialog(int id) {
        AlertDialog dailog = null;
        switch (id) {
        case DIALOG_ADD_CATALOG:
            Builder dailogBuilder = new Builder(this);
            dailogBuilder.setTitle("添加目录");
            dailogBuilder.setView(LayoutInflater.from(this).inflate(R.layout.addcatalog, null));
            dailogBuilder.setNeutralButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }

            });
            dailogBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    //((AlertDialog) dialog).findViewById(id)
                    EditText txtAddCatalogName = (EditText) ((Dialog) dialog).findViewById(R.id.txtAddCatalogName);
                    String strCatalogName = txtAddCatalogName.getEditableText().toString();
                    if (TodoUtil.addCatalog(strCatalogName)) {
                        loadList();
                    }
                }
            });

            dailog = dailogBuilder.create();
            break;
        }
        return dailog;
    }

    // private

    public final AdapterView.OnItemClickListener mainSelectedItemListener =
        new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                long id) {
            Intent it = new Intent(TaskTodo.this, TasksList.class);
            Bundle bundle = new Bundle();
            bundle.putInt(ConstUtil.TASKS_MODE_LIST_KEY, position);
            it.putExtras(bundle);
            startActivity(it);
        }

    };

    /**
     * 初始化画面控件
     */
    private void initCtrl() {
        this.listMain = (ListView) findViewById(R.id.lstCatalog);
        this.txtAllCatalog = (TextView) findViewById(R.id.txtAllCatalog);

        loadList();
    }

    /**
     *
     */
    private void loadList() {
        SimpleAdapter adapter = new SimpleAdapter(this, TodoUtil.getMainData(),
                R.layout.listcatalog, new String[] {
                        ConstUtil.LIST_CATALOG_NAME,
                        ConstUtil.LIST_CATALOG_TASK_NUM }, new int[] {
                        R.id.txtCatalogName, R.id.txtCatalogTasksNum });
        listMain.setAdapter(adapter);
        listMain.setOnItemClickListener(mainSelectedItemListener);
        List lstCatalogNum = TodoUtil.getAllCatalog();
        txtAllCatalog.setVisibility(1);
        if (lstCatalogNum.size() > 0) {
            txtAllCatalog.setVisibility(0);
            SimpleAdapter adapter2 = new SimpleAdapter(this, lstCatalogNum,
                    R.layout.listcatalog, new String[] {
                            ConstUtil.LIST_CATALOG_NAME,
                            ConstUtil.LIST_CATALOG_TASK_NUM }, new int[] {
                            R.id.txtCatalogName, R.id.txtCatalogTasksNum });

            setListAdapter(adapter2);
        }
    }

    /**
     * 初次启动 创建数据库
     */
    private void standby() {

        Log.d(TAG, "Standby 开始");
        // 创建DB链接
        TodoUtil.dbAccess = this.openOrCreateDatabase(ConstUtil.DATABASE_NAME,
                MODE_PRIVATE, null);

        Cursor cursor = TodoUtil.dbAccess.rawQuery(
                "select * from sqlite_master", null);

        // android_metadata 以外其他表存在的话
        if (cursor.getCount() <= 1) {
            Log.d(TAG, "初次启动，需要StandBy");
            TodoUtil.initDataTable();
        }
        Log.d(TAG, "Standby 结束");
    }
}
